import { SearchItemType } from '@src/component/AdvancedSearch/advancedSearch';
import { isArray } from '@src/util/type';
/* enum */
import TableNameEnum from '@model/enum/TableNameEnum';
import { ProjectManageFieldNameMappingEnum } from '@model/enum/FieldMappingEnum';

import { fmtDist } from '@src/util/addressUtil'
// 国际化灰度
import useFormMultiLanguage from '@hooks/useFormMultiLanguage'
const { internationalGray } = useFormMultiLanguage()

/**
 * 判断空值
 * @param value
 * @returns
 */
export const isEmptyValue = (value: any) => {
  if (value === null || value === undefined) return true;
  if (value === '') return true;
  if (Array.isArray(value)) return value.length === 0;
  if (typeof value === 'object') return Object.keys(value).length === 0;
  return false;
};

// 条件项类型
type ConditionItemType = {
  property: string;
  operator: string;
  value?: string | number | null;
  inValue?: Array<string | number>;
  betweenValue1?: string;
  betweenValue2?: string;
  key?: string;
};

// 异常原因
const abnormals = [
  'refusedReason',
  'pausedReason',
  'rollbackReason',
  'reallotReason',
  'offedReason',
];

// 业务search接口需要转换部分字段
const TaskInquireConvertFieldNamesToConditionsMap: Record<string, string> = {
  customer: 'customerId',
  product: 'productId',
  tlmName: 'tlmId',
  executor: 'executorUser',
  allotTypeStr: 'allotType',
  onceException: 'flags',
  synergyId: 'synergies',
  tags: 'tagIds',
  customerAreaSelect: 'area', // 客户管理模块 系统设定的区域下拉菜单
  productType: 'productTypeId',
  serviceProviders: 'relationServiceProviderId',
  managerPerson: 'manager', // 项目管理模块 项目负责人
};

/**
 * 生成查询条件
 * @param {Array<SearchItemType>} searchModel
 * @return conditionParams
 */
export function genConditions(searchModel: SearchItemType[] = []) {
  const conditions: ConditionItemType[] = [];
  const systemConditions: ConditionItemType[] = [];
  const balanceConditions: ConditionItemType[] = []; // 兼容结算自定义字段传参


  searchModel.forEach(item => {
    disposeConditionItem(
      item,
      item.field?.isSystem ? systemConditions : (item.field?.setting?.isOpen ? balanceConditions : conditions)
    );
  });
  const conditionParams = {
    conditions,
    systemConditions,
    balanceConditions
  };

  return conditionParams;
}

/**
 * 处理单个查询条件
 */
export function disposeConditionItem(
  item: SearchItemType,
  conditions: ConditionItemType[] = []
) {
  let { field, fieldName, operator, value } = item;

  if (!field) return;

  // 空值结束
  if (isEmptyValue(value)) return;

  // TODO:数坤特殊处理
  if (fieldName == 'shuKunArea') fieldName = 'area'

  // 项目管理 联系人
  if (field.tableName == TableNameEnum.Project && fieldName == ProjectManageFieldNameMappingEnum.Linkman) fieldName = 'linkmanId'

  const { formType, setting, isSystem } = field;
  const valueKey = isArray(value) ? 'inValue' : 'value';
  const condition: ConditionItemType = {
    property:
      TaskInquireConvertFieldNamesToConditionsMap[fieldName] ?? fieldName,
    operator,
  };

  if (['address', 'area'].includes(formType) && fieldName != 'productCompleteAddress') {
    // 系统字段处理方法，地址、区域
    const { country = '', province = '', city = '', dist = '', street = '' } = value;
    
    if(isSystem !== 1){
      // 自定义的地址需要拼成一个字符串
      condition.value = fmtDist(value,'')
      // TODO: 这里的中国不用翻译不用翻译不用翻译！！！！！！！！！！
      // 非国际化租户为了兼容老数据，需要把中国给去除
      if (!internationalGray && condition.value.substring(0, 2) == '中国') {
        condition.value = condition.value.substring(2)
      }
      return conditions.push(condition)
    }
    // 地址
    const address = [];

    // 非国际化不加国家字段，搜索不到结果，国际化且国家是‘中国’也不用提交接口，存在paas升级到国际化租户，老数据搜索不到的问题
    // 这里的中国不用翻译不用翻译不用翻译！！！！！！！！！！
    if (country && internationalGray) {
      address.push({
        property: 'country',
        operator,
        value: country,
      });
    }
    if (province) {
      address.push({
        property: 'province',
        operator,
        value: province,
      });
    }
    if (city) {
      address.push({
        property: 'city',
        operator,
        value: city,
      });
    }
    if (dist) {
      address.push({
        property: 'dist',
        operator,
        value: dist,
      });
    }
    if (street) {
      address.push({
        property: 'street',
        operator,
        value: street,
      });
    }

    return conditions.push(...address);
  } else if (fieldName === 'tags') {
    // 服务部门
    condition.inValue = value.map((v: any) => v.id);
  } else if (
    fieldName === 'customer'
    || ['related_customer', 'related_customers'].includes(formType)
  ) {
    // 客户、 关联客户
    condition.value = value[0].id;
  } else if (fieldName === 'product') {
    // 产品
    condition.value = value.id;
  } else if (['catalogId', 'serviceProviders', 'serviceProviderId'].includes(fieldName)) {
    // 产品类型 | 服务商 | 系统服务商
    condition.value = value.value;
  } else if (fieldName === 'productMenu') {
    // 产品目录 取最后一级的值
    condition.inValue = value.map((item:any) => {
      return (item.length && item[item.length - 1]) || ''
    }).filter(Boolean);
  } else if (fieldName === 'tlmName') {
    // 联系人 --> 工单
    condition.value = value.id;
  } else if (fieldName === 'linkmanId') {
    // 联系人 --> 客户管理
    condition.value = value.id;
  } else if (formType === 'related_task') {
    // 工单编号
    condition.value = value;
    condition.key = 'taskNo';
  } else if (formType === 'user') {
    // 人员选择（创建人、派单人、负责人、协同人等）
    if (isArray(value)) {
      // 备件占用列表人员高级搜索修改
      if (field.tableName === 'partOccupy' && ['claimant', 'executor'].includes(fieldName)) {
        condition.inValue = value.map((item: { name: string }) => item.name);
      }else {
        condition.inValue = value.map((item: { id: string }) => item.id);
      }
    } else {
      condition.value = value.id;
    }
  } else if (abnormals.includes(fieldName)) {
    // 异常原因
    condition.property = field.englishName;
    condition[valueKey] = value;
  } else if (
    ['date', 'datetime', 'planStartTime', 'planEndTime', 'planTime'].includes(formType)
  ) {
    if(['gt', 'lt', 'le', 'ge'].includes(operator)) {
      condition.value = value
    } else{
      condition.betweenValue1 = value[0];
      condition.betweenValue2 = value[1];
    }
  } else if (fieldName === 'isRepeatRepair') {
    condition.inValue = value.map((v: string) => (v === '全部' ? '' : v));
  } else if (fieldName == 'source') {
    condition.inValue = value.map((v: string) => {
      if (v == 'API创建') v = '开放API'
      return v
    })
  } else if (fieldName === 'qualityStatus') {
    condition.value = value == '保内' ? 'IN' : 'OUT';
  } else if (formType === 'cascader') {
    // 多级菜单
    condition.inValue = value;
    if (setting?.isMulti) {
      // 多选
      condition.inValue = value.map((item: string[]) => item.join('/'));
      condition.operator = 'multiSelect'; // 修改条件
    }
  }else if (['taskEstimatedMileage', 'estimatedMileage', 'actualMileage'].includes(formType) && condition.operator === 'between') {
    condition.betweenValue1 = value.betweenValue1;
    condition.betweenValue2 = value.betweenValue2;
  } else if (fieldName === 'svcProjectName') {
    condition.inValue = value.map((v: any) => v.value);
  } else if(fieldName === 'productCustomerMultiAddress') {
    const ret = (value || []).map((item: string[]) => {
      return {
        country: item[0],
        province: item[1] || '',
        city: item[2] || '',
        dist: item[3] || '',
      };
    });
    condition.inValue = ret;
  } else if (fieldName === 'productCompleteAddress') {
    condition.value = `${value?.country || ''}${value?.province || ''}${value?.city || ''}${value?.dist || ''}`
  } else if(formType === 'currency') {
    condition.property = `${field.fieldName}_amount_number`; // 修改条件
    if(condition.operator === 'between') {
      condition.betweenValue1 = value.number[0];
      condition.betweenValue2 = value.number[1];
    } else {
      condition.value = value.number || '';
    }
    condition.inValue = value.currency || [];
  } else if (fieldName === 'tagLabel') {
    // 服务商标签
    condition.value = value.id;
  } else if (fieldName === 'authorizeProduct') {
    // 服务商授权产品目录
    condition.inValue = value.map((item: { id: string }) => item.id);
  } else if (fieldName === 'parentCustomer') {
    // 上级客户
    condition.property = 'parentId';
    condition.inValue = (value || []).map((item: { id: string }) => item.id) ;
  } else {
    // 默认不需要处理的值
    condition[valueKey] = value;
  }

  conditions.push(condition);
}
